package com.homegoods.home.presenters;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.homegoods.aroutercomment.ARouterPath;
import com.homegoods.classify.ui.view.IView;
import com.homegoods.home.HomeApiUtils;
import com.homegoods.home.model.HomeClassModel;
import com.homegoods.home.model.HomeGroupsModel;
import com.homegoods.home.model.OSSConfig;
import com.homegoods.resource.HomeGoodsApp;
import com.kedll.library.mvp.BasePresenter;
import com.kedll.library.util.SharePreUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import io.reactivex.functions.Consumer;


/**
 * @author QiQi
 * @ClassName: HomePresenter
 * @date 2018/9/6
 * @description
 */
public class HomePresenter extends BasePresenter<IView> {

    public HomePresenter(IView mView) {
        super(mView);
    }

    public void getMenuItems() {
        HomeApiUtils.getHomeGroups(homeGroupsModels -> HomePresenter.this.onLoadData(homeGroupsModels),
                throwable -> throwable.printStackTrace());
    }

    public void onLoadData(List<HomeGroupsModel> childList) {
        if (childList.size() == 0) {
            return;
        }
        List<Fragment> fragments = new ArrayList<>();
        String[] titles = new String[childList.size()];
        int j = 0;
        for (int i = 0; i < childList.size(); i++) {
            HomeGroupsModel child = childList.get(i);
            titles[j] = child.getGroupName();
            j++;
            Fragment fragment = (Fragment) ARouter.getInstance().build(ARouterPath.PATH_FRAGMENT_HOMEACTIVITY).navigation();
            Bundle bundle = new Bundle();
            bundle.putSerializable("child", child);
            fragment.setArguments(bundle);
            fragments.add(fragment);
        }
        mView.initViewPager(fragments, titles);
    }

    public void startAppGetDeviceConfig() {
        HomeApiUtils.startAppGetDeviceConfig(new Consumer<String>() {
            @Override
            public void accept(String value) throws Exception {
                SharePreUtils.saveAppConfig(value);
            }
        }, throwable -> {
        });
    }

    public void getOSSConfig() {
        HomeApiUtils.getOssAliyunConfig(ossConfig -> {
            Log.d("zhengshibo", "accept: ossconfig == " + JSON.toJSONString(ossConfig));
            if (ossConfig != null) {
                HomeGoodsApp.setOSSHost(ossConfig.getHost());
                SharePreUtils.savaOssConfig(JSON.toJSONString(ossConfig));
            }
        }, throwable -> {});
    }

}
